package com.example.wanxiang.controller;

import com.example.wanxiang.dto.JwtRequest;
import com.example.wanxiang.dto.JwtResponse;
import com.example.wanxiang.dto.RegisterRequest;
import com.example.wanxiang.entity.User;
import com.example.wanxiang.repository.UserRepository;
import com.example.wanxiang.security.JwtService;
import com.example.wanxiang.service.Impl.AuthService;
import com.example.wanxiang.service.InviteService;
import com.example.wanxiang.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/index")
public class IndexController {

    @Autowired
    private InviteService inviteService;

    @Resource
    private AuthService authService;

    @Resource
    private UserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private JwtService jwtService;

    @PostMapping("/register")
    public JwtResponse register(@RequestBody RegisterRequest request) {
        JwtResponse register =null;
        if (inviteService.deleteInvite(request.getCode())!=null)
         register = authService.register(request);
        else {
            return null;
        }
        if (register == null) {
            throw new RuntimeException("register failed");
        }
        return register;
    }
    // 请求返回null那就是没成功注册码错误

    //    用户登录
    @PostMapping("/login")
    public JwtResponse login(@RequestBody JwtRequest jwtRequest) {
        User byEmail = userService.findByEmail(jwtRequest.getEmail());
        if (passwordEncoder.matches(jwtRequest.getPassword(), byEmail.getPassword())) {
            byEmail.setLoginTime(LocalDateTime.now());
            userService.updateUserLogin(byEmail);
            return new JwtResponse(jwtService.generateToken(byEmail));
        }
        return null;
    }


}
